package org.jeecg.modules.demo.Customer.service.impl;

import org.jeecg.modules.demo.Customer.entity.Customer;
import org.jeecg.modules.demo.Customer.entity.Khdz;
import org.jeecg.modules.demo.Customer.entity.Shdw;
import org.jeecg.modules.demo.Customer.mapper.KhdzMapper;
import org.jeecg.modules.demo.Customer.mapper.ShdwMapper;
import org.jeecg.modules.demo.Customer.mapper.CustomerMapper;
import org.jeecg.modules.demo.Customer.service.ICustomerService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 客户
 * @Author: jeecg-boot
 * @Date:   2021-02-11
 * @Version: V1.0
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

	@Autowired
	private CustomerMapper customerMapper;
	@Autowired
	private KhdzMapper khdzMapper;
	@Autowired
	private ShdwMapper shdwMapper;
	
	@Override
	@Transactional
	public void saveMain(Customer customer, List<Khdz> khdzList,List<Shdw> shdwList) {
		customerMapper.insert(customer);
		if(khdzList!=null && khdzList.size()>0) {
			for(Khdz entity:khdzList) {
				//外键设置
				entity.setCid(customer.getId());
				khdzMapper.insert(entity);
			}
		}
		if(shdwList!=null && shdwList.size()>0) {
			for(Shdw entity:shdwList) {
				//外键设置
				entity.setCid(customer.getId());
				shdwMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(Customer customer,List<Khdz> khdzList,List<Shdw> shdwList) {
		customerMapper.updateById(customer);
		
		//1.先删除子表数据
		khdzMapper.deleteByMainId(customer.getId());
		shdwMapper.deleteByMainId(customer.getId());
		
		//2.子表数据重新插入
		if(khdzList!=null && khdzList.size()>0) {
			for(Khdz entity:khdzList) {
				//外键设置
				entity.setCid(customer.getId());
				khdzMapper.insert(entity);
			}
		}
		if(shdwList!=null && shdwList.size()>0) {
			for(Shdw entity:shdwList) {
				//外键设置
				entity.setCid(customer.getId());
				shdwMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		khdzMapper.deleteByMainId(id);
		shdwMapper.deleteByMainId(id);
		customerMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			khdzMapper.deleteByMainId(id.toString());
			shdwMapper.deleteByMainId(id.toString());
			customerMapper.deleteById(id);
		}
	}
	
}
